const express = require('express');
const router = express.Router();
const { query } = require('../database/db');

const checkPermission = require('../middleware/checkPermission');
const auth = require('../middleware/auth');

// 学生获取自己的考试列表
router.get('/exams', auth, async (req, res) => {
    try {
        const { status, page_size = 10, page = 1 } = req.query;

        let sql = `
            SELECT 
                e.id,
                e.name,
                e.type,
                e.date,
                e.total_score,
                se.status,
                se.total_score AS student_score,
                se.submit_time,
                c.name AS class_name
            FROM exams e
            JOIN student_exams se ON e.id = se.exam_id
            JOIN classes c ON e.class_id = c.id
            WHERE se.student_id = ?
        `;

        let countSql = `SELECT COUNT(*) as total FROM student_exams WHERE student_id = ?`;
        let conditions = [];
        let params = [req.user.id];

        // 添加筛选条件
        if (status) {
            conditions.push(`se.status = ?`);
            params.push(status);
        }

        // 添加WHERE子句
        if (conditions.length > 0) {
            const whereClause = ` AND ${conditions.join(' AND ')}`;
            sql += whereClause;
            countSql += whereClause;
        }

        // 添加排序和分页
        sql += ` ORDER BY e.date DESC LIMIT ? OFFSET ?`;
        params.push(parseInt(page_size), (parseInt(page) - 1) * parseInt(page_size));

        // 执行查询
        const [exams, totalResult] = await Promise.all([
            query(sql, params),
            query(countSql, params.slice(0, -2))
        ]);

        res.json({
            code: 200,
            data: {
                list: exams,
                total: totalResult[0].total,
                page: parseInt(page),
                page_size: parseInt(page_size)
            }
        });
    } catch (error) {
        console.error('获取考试列表失败:', error);
        res.status(500).json({ code: 500, msg: '获取考试列表失败' });
    }
});

// 学生开始考试
router.post('/exams/:id/start', auth, async (req, res) => {
    const { id: exam_id } = req.params;

    try {
        // 检查考试是否存在
        const [exam] = await query('SELECT * FROM exams WHERE id = ?', [exam_id]);
        if (!exam) {
            return res.status(404).json({ code: 404, msg: '考试不存在' });
        }

        // 检查是否已分配考试
        const [studentExam] = await query(
            'SELECT * FROM student_exams WHERE student_id = ? AND exam_id = ?',
            [req.user.id, exam_id]
        );

        if (!studentExam) {
            return res.status(403).json({ code: 403, msg: '您未被分配参加此考试' });
        }

        // 检查考试状态
        if (studentExam.status !== 1) {
            return res.status(400).json({
                code: 400,
                msg: studentExam.status === 2 ? '考试已开始' : '考试已完成'
            });
        }

        // 更新考试状态为进行中
        await query(
            'UPDATE student_exams SET status = 2, start_time = NOW() WHERE id = ?',
            [studentExam.id]
        );

        res.json({
            code: 200,
            msg: '考试已开始',
            data: { student_exam_id: studentExam.id }
        });
    } catch (error) {
        console.error('开始考试失败:', error);
        res.status(500).json({ code: 500, msg: '开始考试失败' });
    }
});

// 学生获取考试题目
router.get('/exams/:id/questions', auth, async (req, res) => {
    const { id: exam_id } = req.params;

    try {
        // 检查考试状态
        const [studentExam] = await query(
            'SELECT * FROM student_exams WHERE student_id = ? AND exam_id = ?',
            [req.user.id, exam_id]
        );

        if (!studentExam) {
            return res.status(403).json({ code: 403, msg: '您未被分配参加此考试' });
        }

        if (studentExam.status === 1) {
            return res.status(403).json({ code: 403, msg: '考试未开始' });
        }

        if (studentExam.status === 3) {
            return res.status(403).json({ code: 403, msg: '考试已完成' });
        }

        // 获取题目
        const [questions] = await query(
            'SELECT * FROM exam_questions WHERE exam_id = ? ORDER BY question_order',
            [exam_id]
        );

        // 获取已提交的答案
        const [answers] = await query(
            'SELECT question_id, answer_text FROM student_answers WHERE student_exam_id = ?',
            [studentExam.id]
        );

        const answerMap = {};
        answers.forEach(answer => {
            answerMap[answer.question_id] = answer.answer_text;
        });

        // 合并题目和答案
        const result = questions.map(question => ({
            ...question,
            student_answer: answerMap[question.question_id] || null
        }));

        res.json({
            code: 200,
            data: result
        });
    } catch (error) {
        console.error('获取考试题目失败:', error);
        res.status(500).json({ code: 500, msg: '获取考试题目失败' });
    }
});

// 学生提交答案
router.post('/exams/:id/answers', auth, async (req, res) => {
    const { id: exam_id } = req.params;
    const { answers } = req.body; // [{question_id, answer_text}]

    try {
        // 检查考试状态
        const [studentExam] = await query(
            'SELECT * FROM student_exams WHERE student_id = ? AND exam_id = ?',
            [req.user.id, exam_id]
        );

        if (!studentExam) {
            return res.status(403).json({ code: 403, msg: '您未被分配参加此考试' });
        }

        if (studentExam.status !== 2) {
            return res.status(400).json({
                code: 400,
                msg: studentExam.status === 1 ? '考试未开始' : '考试已完成'
            });
        }

        // 批量插入或更新答案
        for (const answer of answers) {
            await query(
                `INSERT INTO student_answers 
                 (student_exam_id, question_id, answer_text) 
                 VALUES (?, ?, ?) 
                 ON DUPLICATE KEY UPDATE answer_text = VALUES(answer_text)`,
                [studentExam.id, answer.question_id, answer.answer_text]
            );
        }

        res.json({
            code: 200,
            msg: '答案提交成功'
        });
    } catch (error) {
        console.error('提交答案失败:', error);
        res.status(500).json({ code: 500, msg: '提交答案失败' });
    }
});

// 学生提交考试
router.post('/exams/:id/submit', auth, async (req, res) => {
    const { id: exam_id } = req.params;

    try {
        // 检查考试状态
        const [studentExam] = await query(
            'SELECT * FROM student_exams WHERE student_id = ? AND exam_id = ?',
            [req.user.id, exam_id]
        );

        if (!studentExam) {
            return res.status(403).json({ code: 403, msg: '您未被分配参加此考试' });
        }

        if (studentExam.status !== 2) {
            return res.status(400).json({
                code: 400,
                msg: studentExam.status === 1 ? '考试未开始' : '考试已完成'
            });
        }

        // 更新考试状态为已完成
        await query(
            'UPDATE student_exams SET status = 3, submit_time = NOW() WHERE id = ?',
            [studentExam.id]
        );

        res.json({
            code: 200,
            msg: '考试提交成功'
        });
    } catch (error) {
        console.error('提交考试失败:', error);
        res.status(500).json({ code: 500, msg: '提交考试失败' });
    }
});

// 学生查看考试结果
router.get('/exams/:id/results', auth, async (req, res) => {
    const { id: exam_id } = req.params;

    try {
        // 检查考试状态
        const [studentExam] = await query(
            'SELECT * FROM student_exams WHERE student_id = ? AND exam_id = ?',
            [req.user.id, exam_id]
        );

        if (!studentExam) {
            return res.status(403).json({ code: 403, msg: '您未被分配参加此考试' });
        }

        if (studentExam.status !== 3) {
            return res.status(400).json({
                code: 400,
                msg: '考试未完成，无法查看结果'
            });
        }

        // 获取考试基本信息
        const [exam] = await query('SELECT * FROM exams WHERE id = ?', [exam_id]);

        // 获取题目和答案
        const [results] = await query(`
            SELECT 
                eq.question_id,
                eq.question_text,
                eq.question_type,
                eq.score AS max_score,
                sa.answer_text,
                sa.score,
                sa.teacher_comment
            FROM exam_questions eq
            LEFT JOIN student_answers sa ON eq.question_id = sa.question_id AND sa.student_exam_id = ?
            WHERE eq.exam_id = ?
            ORDER BY eq.question_order
        `, [studentExam.id, exam_id]);

        res.json({
            code: 200,
            data: {
                exam: {
                    id: exam.id,
                    name: exam.name,
                    total_score: exam.total_score,
                    student_score: studentExam.total_score
                },
                questions: results
            }
        });
    } catch (error) {
        console.error('获取考试结果失败:', error);
        res.status(500).json({ code: 500, msg: '获取考试结果失败' });
    }
});

module.exports = router;